import json
from common.notify import NotifyMap
from model.model import NotifyConfigure
from common.cache import notify_cache


class NotifyView(NotifyConfigure):
    
    @classmethod
    def verify(cls, type, configure, **kwargs):
        try:
            item = NotifyMap[type](**configure)
            item.verify(**kwargs)
            return 0
        except Exception as e:
            return -1
    
    @classmethod
    def create_notify(cls, session, body):
        item = cls.create_item(session, body)
        notify_cache.set({item.id: json.dumps({'id': item.id, 'name': item.name, 'type': item.type, 
                                               'configure': item.configure}, ensure_ascii=False)})
        return item

    @classmethod
    def update_notify(cls, session, filter_, update):
        item = cls.update_item(session, filter_=filter_, update=update)
        notify_cache.set({item.id: json.dumps({'id': item.id, 'name': item.name, 'type': item.type, 
                                               'configure': item.configure}, ensure_ascii=False)})
        return item


    @classmethod
    def delete_notifies(cls, session, filter_):
        items = cls.get_items(session, filter_)
        notify_cache.delete([item.id for item in items.id])
        return cls.delete_items(session, filter_)

    @classmethod
    def load_notify_cache(cls, session):
        """缓存信息"""
        notifies = session.query(NotifyConfigure).all()
        notify_cache.set({item.id: json.dumps({'name': item.name, 'type': item.type, 'configure': item.configure}, ensure_ascii=False) 
                          for item in notifies})
